#include "blank_parser.h"
#include "blank_parser/parser.h"
#include <iostream>

using namespace std;

void parsed(void* userdata, char *tag, char **attr)
{
	network::blank_parser *bp = (network::blank_parser*) userdata;
	boost::shared_ptr<model::dom> d(new model::dom(tag));
	for(int i = 0; attr[i] && attr[i + 1]; i = i + 2) {
		if(attr[i + 1]) {
			d->insert_attrib(attr[i], attr[i + 1]);
		}
	}
	bp->add_dom(d);
}

network::blank_parser::blank_parser()
{
	_pars = ::parser_create();
	_pars->userdata = (void*) this;
	_pars->callback = &parsed;
}

network::blank_parser::~blank_parser()
{
	parser_delete(_pars);
}

boost::shared_ptr<model::dom> network::blank_parser::parse(const string &msg)
{
	boost::mutex::scoped_lock l(_mutex);
	_dom.reset();
	for(int i = 0; i < msg.size(); ++i) {
		parse_add(_pars, msg[i]);
		::parse(_pars);
	}
	if(_dom.get() == 0) {
		throw network::parse_exception(
			"parse_exception in blank_parser");
	}
	return _dom;
}

void network::blank_parser::add_dom(boost::shared_ptr<model::dom> d)
{
	if(_dom.get() == 0) {
		_dom.reset(new model::dom(*d));
	} else {
		_dom->insert_node(*d);
	}
}

